//
//  HYUserViewController.m
//  HaiYue
//
//  Created by skyline on 2018/6/14.
//  Copyright © 2018年 skyline. All rights reserved.
//

#import "HYUserViewController.h"
#import "HYPickPhotoViewController.h"
#import "HYUserCell.h"
#import <AFNetworking.h>
CGFloat const HYLOGINOUTHEITHG = 44;
@interface HYUserViewController ()<UITableViewDelegate,UITableViewDataSource,NSURLSessionDelegate>
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) HYButton *button;
@property (nonatomic, strong) HYUserModel *userModel;
@property (nonatomic, strong) UIImage *image;
@property (nonatomic, strong) NSArray *array;
@property (nonatomic, strong) UIImagePickerController *picker;
@end

@implementation HYUserViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"个人资料";
    [CCNotice addObs:self sel:@selector(actionForUploadImage:) name:CCNoticeNameHYPickPhoto obj:nil];
    CCGradientLayer *layer = [CCGradientLayer layerWithColors:@[(__bridge id)THEME_COLOR.CGColor,(__bridge id)[UIColor whiteColor].CGColor] locations:@[@0.3, @0.5, @1.0] startPoint:CGPointMake(0, 0) endPoint:CGPointMake(0, 1.0) frame:self.view.frame];
    [self.view.layer addSublayer:layer];
    // Do any additional setup after loading the view.
}

- (UITableView *)tableView
{
    if (!_tableView)
    {
        _tableView = [[UITableView alloc] init];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.bounces = NO;
        _tableView.backgroundColor = [UIColor clearColor];
        [self.view addSubview:_tableView];
        [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.mas_offset(UIEdgeInsetsMake(GAP, GAP, HYLOGINOUTHEITHG + GAP, GAP));
        }];
    }
    return _tableView;
}

- (HYButton *)button
{
    if (!_button)
    {
        _button = [[HYButton alloc] initWithTitle:@"退出登录" backColor:THEME_COLOR];
        [_button addTarget:self action:@selector(actionForLoginOut:) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:_button];
        [_button mas_makeConstraints:^(MASConstraintMaker *make) {
            make.bottom.equalTo(self.view).with.offset(- GAP);
            make.left.equalTo(self.view).with.offset(GAP);
            make.right.equalTo(self.view).with.offset(-GAP);
            make.height.mas_offset(HYLOGINOUTHEITHG);
        }];
    }
    return _button;
}

- (UIImage *)image
{
    if (!_image)
    {
        return ([self.userModel.photo length] > 1) ? [UIImage imageWithURL:self.userModel.photo]: [UIImage imageNamed:@"default_gameicon"];
    }
    return _image;
}
- (void)setUserModel:(HYUserModel *)userModel
{
    if (_userModel != userModel)
    {
        _userModel = userModel;
        [self.tableView reloadData];
    }
}
- (NSArray *)array
{
    return @[@[@"账号ID",@"头像",@"昵称",@"手机号",@"地区"],@[@"登录密码",@"支付密码",@"身份证",@"收货人",@"收货电话",@"收货地址"]];
}

- (void)actionForUploadImage:(NSNotification *)notify
{
    self.image = (UIImage *)[notify.userInfo valueForKey:@"image"];
    NSData *imgdata = UIImagePNGRepresentation(self.image);
    [CCHttp upload:AIP_UPLOAD_PHOTO para:@{@"terminal":@"1",@"accesstoken":[HYUserManager manager].user.accesstoken} data:imgdata progress:^(NSURLSession * _Nonnull session, NSProgress * _Nonnull progress) {
        NSLog(@"已经上传 ==  %@",progress.localizedDescription);
    } success:^(id  _Nonnull response) {
        NSLog(@"dict == %@",response);
    } fail:^(NSError * _Nonnull error) {
        NSLog(@"error == %@", error);
    }];
}
- (void)actionForLoginOut:(HYButton *)sender
{
    [CCAlert showMessage:@"退出本账号，是否继续" title:@"注意" leftBtnText:@"非常确定" rightBtnText:@"我再想想" leftblock:^{
        [self startHUD];
        [CCHttp post:API_DO_LOGOUT para:@{@"account":self.userModel.account} success:^(id  _Nonnull response) {
            [self endHUD];
            HYUserModel *model = [HYUserModel mj_objectWithKeyValues:response];
            [CCSave archiver:model toFile:USER_MODEL];
            [CCAlert showMessage:@"已退出登录" hidden:^{
                [self.navigationController popViewControllerAnimated:YES];
            }];
        } fail:^(NSError * _Nonnull error) {
            [self endHUD];
        }];
        
//        [HYHttps post:API_DO_LOGOUT para:@{@"account":self.userModel.account} complete:^(id response) {
//            [self endHUD];
//            HYUserModel *model = [HYUserModel mj_objectWithKeyValues:response];
//            [CCSave archiver:model toFile:USER_MODEL];
//            [CCAlert showMessage:@"已退出登录" hidden:^{
//                [self.navigationController popViewControllerAnimated:YES];
//            }];
//        } fail:^(NSDictionary *dict) {
//
//        }];
    } rightBlock:nil];
}

- (void)httpRequest
{
    [self startHUD];
    [CCHttp post:API_USER_MYDATA para:nil success:^(id  _Nonnull response) {
        HYUserModel *model = [HYUserModel mj_objectWithKeyValues:response];
        model.accesstoken = [HYUserManager manager].user.accesstoken;
        model.passmm = [HYUserManager manager].user.passmm;
        self.userModel = model;
        [CCSave archiver:model toFile:USER_MODEL];
        [self endHUD];
    } fail:^(NSError * _Nonnull error) {
        [self endHUD];
        self.userModel = [CCSave unarchiverObjFromFile:USER_MODEL];
    }];
//    [HYHttps post:API_USER_MYDATA para:nil complete:^(id response) {
//        HYUserModel *model = [HYUserModel mj_objectWithKeyValues:response];
//        model.accesstoken = [HYUserManager manager].user.accesstoken;
//        model.passmm = [HYUserManager manager].user.passmm;
//        self.userModel = model;
//        [CCSave archiver:model toFile:USER_MODEL];
//        [self endHUD];
//    } fail:^(NSDictionary *dict) {
//        [self endHUD];
//        self.userModel = [CCSave unarchiverObjFromFile:USER_MODEL];
//    }];
}
#pragma mark - UITableViewDataSource method
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) return 5;
    else return 6;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.array.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString * identifier = [NSString stringWithFormat:@"HYUserCell%d%d",(int)indexPath.section, (int)indexPath.row];
    HYUserCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (!cell)
    {
        cell = [[HYUserCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
    }
    if (indexPath.section == 1 || (indexPath.section == 0 && (indexPath.row == 1 || indexPath.row == 2)))
    {
        cell.rightArrowIMG.hidden = NO;
        cell.selectionStyle = UITableViewCellSeparatorStyleSingleLine;
    }
    if (indexPath.section == 0)
    {
        if (indexPath.row == 0)
            cell.contentLBL.text = self.userModel.accountid;
        else if (indexPath.row == 1 )
            cell.img.image = self.image;
        else if (indexPath.row == 2)
            cell.contentLBL.text = self.userModel.nickname;
        else if (indexPath.row == 3)
            cell.contentLBL.text = self.userModel.phone;
        else if (indexPath.row == 4)
            cell.contentLBL.text = self.userModel.area;
    }
    else
    {
        
    }
    cell.line.hidden = (indexPath.section == 1 && indexPath.row == 5)?YES:NO;
    cell.titleLBL.text = self.array[indexPath.section][indexPath.row];
    return cell;
}
#pragma mark - UITableViewDelegate method

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    if (section == 0) return GAP;
    return 0;
}

- (nullable UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    if (section == 0)  return [[HYView alloc] initWithColor:[UIColor clearColor]];
    else return nil;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.section == 0 && indexPath.row == 1)
    {
        HYPickPhotoViewController *picker = [[HYPickPhotoViewController alloc] init];
        [CCAlert sheet:nil title:nil sheetTitles:@[@"去相机",@"去相册"] block:^(int index) {
            picker.sourceType = (index == 0)?UIImagePickerControllerSourceTypeCamera:UIImagePickerControllerSourceTypePhotoLibrary;
            [self startHUD];
            [self presentViewController:picker animated:NO completion:^{
                [self endHUD];
            }];
        }];
    }
    else if (indexPath.section == 0 && indexPath.row == 2)
    {
        id vc = [NSClassFromString(@"HYNickNameViewController") new];
        [vc setValue:self.userModel.nickname forKey:@"oldName"];
        [self.navigationController pushViewController:vc animated:YES];
    }
    else if (indexPath.section == 1 && indexPath.row == 0)
    {
        
    }
    else if (indexPath.section == 1 && indexPath.row == 1)
    {
        
    }
    else if (indexPath.section == 1 && indexPath.row == 2)
    {
        
    }
    else if (indexPath.section == 1 && indexPath.row == 3)
    {
        
    }
    else if (indexPath.section == 1 && indexPath.row == 4)
    {
        
    }
    else if (indexPath.section == 1 && indexPath.row == 5)
    {
        
    }
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.style = HYViewNaviBarStyleOnlyLeftBtn;
    self.button.hidden = NO;
    self.userModel = [CCSave unarchiverObjFromFile:USER_MODEL];
    [self httpRequest];
}
- (void)dealloc
{
    [CCNotice rmObs:self name:CCNoticeNameHYPickPhoto obj:nil];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
